package com.chuantou.yuba.adapter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.to.FriendTO;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.DateUtil;
import com.chuantou.yuba.util.ViewHolder;

public class FriendAdapter extends BaseAdapter {
	private List<FriendTO> mFriends = new ArrayList<FriendTO>();
	private Context mContext;

	public FriendAdapter(Context context) {
		this.mContext = context;
	}

	@Override
	public int getCount() {
		return mFriends.size();
	}

	@Override
	public Object getItem(int position) {
		return mFriends.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void add(List<FriendTO> friends) {
		if (friends != null && !friends.isEmpty()) {
			mFriends.addAll(friends);
		}
	}

	public void clear() {
		mFriends.clear();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = View.inflate(mContext, R.layout.friend_item, null);
		}
		FriendTO friend = mFriends.get(position);
		NetworkImageView avatarView = ViewHolder.get(convertView, R.id.avatar);
		BitmapBinder.bindCircularNetImage(mContext, avatarView, friend.getAvatar(), R.drawable.default_avatar_round_small);
		TextView sexView = ViewHolder.get(convertView, R.id.sex);
		int sex = friend.getSex();
		if (sex == Constants.SEX_FEMALE) {
			sexView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sex_female, 0, 0, 0);
			sexView.setTextColor(mContext.getResources().getColor(R.color.sex_color_female));
		} else {
			sexView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sex_male, 0, 0, 0);
			sexView.setTextColor(mContext.getResources().getColor(R.color.sex_color_male));
		}
		Date date = DateUtil.getDateObj(friend.getBirthday(), DateUtil.PATTERN_YMD);
		int age = (int) ((System.currentTimeMillis() - date.getTime()) / (365L * 24 * 60 * 60 * 1000));
		sexView.setText(String.valueOf(age));
		TextView nicenameView = ViewHolder.get(convertView, R.id.nickname);
		nicenameView.setText(friend.getNickname());
		TextView moodView = ViewHolder.get(convertView, R.id.mood);
		moodView.setText(friend.getMood());
		return convertView;
	}
}
